#! /usr/bin/env python
#coding=utf-8
import  sys,urllib2,json,time,datetime
import MySQLdb
import multiprocessing
reload(sys)

#正式连接-----------
#host = "drdsrtok600s5n74.drds.aliyuncs.com"
#user = "hefantv"
#passwd = "HEfantv3_9a5"
#db = "hefantv"
#测试连接--------------
host = "drdsjsq4v76a23pa.drds.aliyuncs.com"
user = "hefantest"
passwd = "HEfantv3_9a5"
db = "hefantest"
#开发连接--------------
#host = "drdshmif9192k8au.drds.aliyuncs.com"
#user = "hefandev"
#passwd = "devhfDEV8v97"
#db = "hefandev"
port = 3306
charset='utf8'

#获取token的请求地址
#开发地址
#tokenUrl = "http://47.93.91.24:8055"
#QA请求地址
tokenUrl = "http://101.200.198.81:8055"
#生产请求地址
#tokenUrl = "http://10.51.68.107:8055"
#融云获取token所需默认的头像地址
defalutHeadImg = "http://img.hefantv.com/default_head.png"
#初始化用户数量控制
initCount = 50000
#批量新增记录数
bachNum = 500
#测试使用前缀用户注册token的前缀
prefix = ""

def queryMaxIdFromQuence(connect) :
    cursor = connect.cursor()
    try :
        sql = "SELECT user_id_pub_seq.NEXTVAL FROM DUAL"
        cursor.execute(sql)
        data = cursor.fetchone()
        cursor.close()
        return data[0]+1
    except Exception,e:
        return 0


def queryMaxUserId():
    maxId = 0;
    connect = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, port=port, charset=charset)
    cursor = connect.cursor()
    sql = "select max(CONVERT(user_id,SIGNED)) FROM hf_user_pre_init"
    cursor.execute(sql)
    data = cursor.fetchone()
    cursor.close();
    #print data
    if data :
        maxId = data[0]+1
    else:
        maxId = queryMaxIdFromQuence(connect)
    connect.close()
    return maxId

#
# 获取云信im的token
#
def httpClientGetImToken(userId) :
    reqUrl = "%s/services/imUser/createUser?accid=%s&name=%s" % (tokenUrl,userId,userId)
    req = urllib2.Request(reqUrl)
    res_data = urllib2.urlopen(req, timeout=10)
    resData = json.loads(res_data.read())
    print "YxRequestData-------", resData;
    if resData["code"] == 1000 and resData["data"] :
        return resData["data"]
    else:
        return ""

#
# 获取融云im的token
#
def getRyTokenReq(userId) :
    reqUrl = "%s/services/rongIm/getToken?userId=%s&name=%s&portraitUri=%s" % (tokenUrl, userId, userId,defalutHeadImg)
    req = urllib2.Request(reqUrl)
    res_data = urllib2.urlopen(req, timeout=10)
    resData = json.loads(res_data.read())
    print "RyRequestData-------",resData;
    time.sleep(0.005)
    if resData["code"] == 1000 and resData["data"] :
        return resData["data"]
    else:
        return ""

def getBachImToken(stepNum,beginUserId):
    resData = []
    for j in range((stepNum-1)*bachNum,(stepNum-1)*bachNum+bachNum):
        if j>=initCount :
            break
        resData.append(str(beginUserId+j))
    return resData;

def saveBachUserInfo(datas) :
    strArray = []
    for data in datas :
        if data:
            imToken = httpClientGetImToken(prefix+data)
            ryToken = getRyTokenReq(prefix+data)
            if imToken or ryToken:
                strArray.append("('%s','%s','%s')"%(data,imToken,ryToken));
        time.sleep(0.005)
    if len(strArray) > 0 :
        connect = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, port=port, charset=charset)
        cursor = connect.cursor()
        sql = "insert into hf_user_pre_init(user_id,im_token,im_token_ry) values " + ",".join(strArray)
        cursor.execute(sql)
        connect.commit()
        cursor.close()
        connect.close()

def GetNewUser(i,beginUserId):
    bachData = getBachImToken(i,beginUserId)
    saveBachUserInfo(bachData)

if __name__ =='__main__' :
    beginTime = time.clock()
    runDate = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S');
    beginUserId = queryMaxUserId();
    if beginUserId == 0 or beginUserId >=9999999 :
        print "userId:[%s] 不符合条件----"%(str(beginUserId))
    else:
        lock = multiprocessing.Lock()
        mgr = multiprocessing.Manager()
        threads = []
        setp = initCount/bachNum + (1 if initCount%bachNum > 0 else 0);
        for i in range(1,setp+1) :
            t_thread = multiprocessing.Process(target=GetNewUser,args=(i,beginUserId,))
            print "-----t_thread start [%d]----"%(i)
            t_thread.start();
            threads.append(t_thread)
        for t_thread in threads:
            t_thread.join()
            print "-----t_thread end ----"
    print "user pre init end beginUserId:[%d] date:[%s] time:%d s" % (beginUserId,runDate,time.clock() - beginTime)
